#include <stdio.h>
#include <string.h>
#include "Msg.h"

MSG     gMsg[DEFAULT_MSGQ_LEN];
MSG_Q   gMsgQueue;

void DIB542_MsgInit(void)
{
    memset(gMsg, 0, sizeof(MSG) * DEFAULT_MSGQ_LEN);
    memset(&gMsgQueue, 0, sizeof(MSG_Q));

    gMsgQueue.MaxMsgCount = DEFAULT_MSGQ_LEN;
    gMsgQueue.pMsg = (P_MSG)gMsg;
}

int DIB542_MsgPost(MSG_ID msgId, uint32_t wParam)
{
    uint32_t NewWriteMsgIndex;

    NewWriteMsgIndex = ((gMsgQueue.WriteMsgIndex + 1) & (gMsgQueue.MaxMsgCount - 1));
    if(NewWriteMsgIndex == gMsgQueue.ReadMsgIndex)
    {
        /*Message Queue is full*/
        return (-1);
    }

    gMsgQueue.pMsg[gMsgQueue.WriteMsgIndex].MsgId = msgId;
    gMsgQueue.pMsg[gMsgQueue.WriteMsgIndex].MsgWParam = wParam;
    gMsgQueue.WriteMsgIndex = NewWriteMsgIndex;

    return 0;
}

int DIB542_MsgGet(int* pMsgId, uint32_t* pWParam)
{
    uint32_t NewReadMsgIndex;

    NewReadMsgIndex = ((gMsgQueue.ReadMsgIndex + 1) & (gMsgQueue.MaxMsgCount - 1));
    if(gMsgQueue.ReadMsgIndex == gMsgQueue.WriteMsgIndex)
    {
        /*Msg Queue is Empty*/
        return -1;
    }

    *pMsgId = gMsgQueue.pMsg[gMsgQueue.ReadMsgIndex].MsgId;
    *pWParam = gMsgQueue.pMsg[gMsgQueue.ReadMsgIndex].MsgWParam;
    gMsgQueue.pMsg[gMsgQueue.ReadMsgIndex].MsgId = DIB542_MSG_NULL;
    gMsgQueue.ReadMsgIndex = NewReadMsgIndex;

    return 0;
}

